package tests

import (
	"fmt"
	"github.com/gorilla/sessions"
	"github.com/labstack/echo"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/middleware"
	"github.com/labstack/gommon/log"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
	"gopkg.in/go-playground/validator.v9"
	"maki/model"
	"maki/utils"
	"net/http"
	"net/http/httptest"
)

const SuccessMsg = `{"err": null,"data":"success"}`

type TestCase struct {
	suite.Suite
	app *echo.Echo
}

func (t *TestCase) Init() {
	t.app = NewTestingAPP()
}

func (t *TestCase) NewCase(req *http.Request, login bool) (echo.Context, *httptest.ResponseRecorder) {
	req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
	rec := httptest.NewRecorder()
	c := t.app.NewContext(req, rec)
	if login {
		user := model.CreateSampleUser("test", "test123")
		c.Set("user", user)
	}
	return c, rec
}

func (t *TestCase) NewAssert() *assert.Assertions {
	return assert.New(t.T())
}

type testingValidator struct {
	validator *validator.Validate
}

func (cv *testingValidator) Validate(i interface{}) error {
	return cv.validator.Struct(i)
}

func NewTestingAPP() *echo.Echo {
	fmt.Println("echo.Version: ", echo.Version)
	app := echo.New()
	app.Debug = true
	app.Logger.SetLevel(log.DEBUG)

	// custom app
	app.HTTPErrorHandler = utils.ErrorHandler
	app.Validator = &testingValidator{validator: validator.New()}

	// Global middleware
	app.Use(middleware.Logger())

	store := sessions.NewCookieStore([]byte("secret"))
	store.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   3600 * 24 * 7,
		Secure:   false,
		HttpOnly: true,
	}
	app.Use(session.Middleware(store))
	return app
}
